package com.behelpful.demo.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.behelpful.common.integration.iredis.annotation.ThreadJedis;
import com.behelpful.common.integration.iredis.support.IRedisUtil;
import com.behelpful.demo.search.constant.CacheEnum;
import com.behelpful.demo.search.entity.SqlSchemaColumn;
import com.behelpful.demo.search.mapper.SqlSchemaColumnMapper;
import com.behelpful.demo.search.service.SqlSchemaColumnService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 查询获得数据库中表结构
 *
 * @author Alay
 * @date 2020-12-29 18:04
 * @project behelpful
 */
@Service
public class SqlSchemaColumnServiceImpl extends ServiceImpl<SqlSchemaColumnMapper, SqlSchemaColumn> implements SqlSchemaColumnService {

    @Autowired
    private IRedisUtil iRedisUtil;

    /**
     * 此方法不可类内部调用，否则使用AOP处理Jedis将不会关闭
     * 保证字段的顺序，故用RedisZSet 进行存储
     *
     * @param database
     * @param tableName
     * @return
     */
    @ThreadJedis
    @Override
    public String[] columnsByTable(String database, String tableName) {
        String key = CacheEnum.SQL_SCHEMA.key + database + "." + tableName;
        Jedis jedis = iRedisUtil.threadJedis();
        jedis.select(CacheEnum.SQL_SCHEMA.index);
        Boolean exists = jedis.exists(key);
        String[] columnNames;
        if (exists) {
            // 集合中所有成员数
            Long total = jedis.zcard(key);
            columnNames = new String[total.intValue()];
            for (int i = 0; i < total; i++) {
                Set<String> columns = jedis.zrange(key, i, i);
                String column = columns.iterator().next();
                columnNames[i] = column;
            }
        } else {
            // 查询数据表结构存入缓存
            List<SqlSchemaColumn> schemaColumns = this.schemaColumns(database, tableName);

            List<String> columns = schemaColumns.stream().map(SqlSchemaColumn::getColumnName).collect(Collectors.toList());

            columnNames = new String[columns.size()];
            for (int i = 0; i < columns.size(); i++) {
                columnNames[i] = columns.get(i);
                // 存入缓存
                jedis.zadd(key, i + 1, columns.get(i));
            }
        }
        return columnNames;
    }


    private List<SqlSchemaColumn> schemaColumns(String database, String tableName){
        List<SqlSchemaColumn> schemaColumns = this.list(Wrappers.<SqlSchemaColumn>lambdaQuery()
                .eq(SqlSchemaColumn::getTableSchema, database)
                .eq(SqlSchemaColumn::getTableName, tableName)
                .orderByAsc(SqlSchemaColumn::getOrdinalPosition));
        return schemaColumns;
    }

    @ThreadJedis
    @Override
    public boolean removeTableColumn(String database, String tableName) {
        String key = CacheEnum.SQL_SCHEMA.key + database + "." + tableName;
        Jedis jedis = iRedisUtil.threadJedis();
        jedis.select(CacheEnum.SQL_SCHEMA.index);
        Long del = jedis.del(key);
        return del > 0;
    }
}